package com.pro.app.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.app.annotation.LoginUser;
import com.pro.app.dao.UserToken;
import com.pro.app.service.ProTokenManager;
import com.pro.core.util.ResponseUtil;
import com.pro.core.validator.NotNullValidator;
import com.pro.db.domain.BbsComment;
import com.pro.db.domain.BbsTopic;
import com.pro.db.domain.ProUser;
import com.pro.db.service.itf.IBbsCommentService;
import com.pro.db.service.itf.IBbsTopicService;
import com.pro.db.service.itf.IProUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toComplex;

/**
 * 用户服务
 */
@RestController
@RequestMapping("/app/user")
@Validated
public class AppAuthController {
    private final Log logger = LogFactory.getLog(AppAuthController.class);

    @Autowired
    private IProUserService userService;

    @Autowired
    private IBbsTopicService topicService;

    @Autowired
    private IBbsCommentService commentService;

    /**
     * @apiDefine user 用户接口
     *
     */

    /**
     * @api {POST} /app/user/login 2.1 用户登陆
     * @apiName  user login
     * @apiGroup  user
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} username 用户名
     * @apiParam {String} password 密码(MD5加密后的密码）
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/login")
    public Object login(@RequestBody ProUser entity) {
        ComplexResult check = FluentValidator.checkAll()
                .on(entity, new NotNullValidator("用户"))
                .on(entity.getUsername(), new NotNullValidator("用户名"))
                .on(entity.getPassword(), new NotNullValidator("密码"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        ProUser user = userService.getOne(new QueryWrapper<ProUser>()
            .eq("username",entity.getUsername())
            .eq("deleted",0));

        if(null == user){
            return ResponseUtil.fail("用户不存在");
        }

        if(!user.getPassword().equals(entity.getPassword())){
            return ResponseUtil.fail("密码不正确");
        }

        if(!user.getStatus().equals(0)){
            return ResponseUtil.fail("用户不可用");
        }

        // token
        UserToken mercToken = ProTokenManager.generateToken(user.getId(), user.getUsername());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", mercToken.getToken());
        result.put("tokenExpire", mercToken.getExpireTime().toString());
        result.put("userInfo", user);
        return ResponseUtil.ok(result);
    }


    /**
     * @api {POST} /app/user/logout 2.2 退出登陆
     * @apiName  user logout
     * @apiGroup  user
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiHeader {String} X-Litemall-Token 用户授权token
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("logout")
    public Object logout(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        ProTokenManager.removeToken(userId);
        return ResponseUtil.ok();
    }

    /**
     * @api {GET} /app/user/topics 2.3 我的帖子列表
     * @apiName  user topics
     * @apiGroup  user
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiHeader {String} X-Litemall-Token 用户授权token
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("topics")
    public Object topics(@LoginUser Integer userId,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Page<BbsTopic> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<BbsTopic> pList = topicService.page(pageVo,
                new QueryWrapper<BbsTopic>()
                        .select("id","site_id","forum_id","name","description","cover_url",
                                "cover_type","label","keywords","read_num","like_num",
                                "favor_num","hot_tag","create_user_id","create_username",
                                "create_nickname","create_avatar")
                        .eq("deleted",0)
                        .eq("user_id",userId)
                        .orderByDesc("add_time"));
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /app/user/comments 2.4 我的评论列表
     * @apiName  user comments
     * @apiGroup  user
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiHeader {String} X-Litemall-Token 用户授权token
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("comments")
    public Object comments(@LoginUser Integer userId,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Page<BbsComment> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<BbsComment> pList = commentService.getMyComments(pageVo,
               userId);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }
}
